export function addZero(num) {
  // 将num转换为字符串类型，并在左边补‘0’，使其总长度为2
  return String(num).padStart(2, '0')
}

export function getTextLen(str) {
  if (str == null) return 0
  if (typeof str != 'string') {
    str += ''
  }
  return str.replace(/[^\x00-\xff]/g, '01').length
}

export function subTextLen(str, len) {
  let realLength = 0
  let charCode = -1
  let result = ''
  for (let i = 0; i < str.length && realLength < len; i++) {
    charCode = str.charCodeAt(i)
    if (charCode >= 0 && charCode <= 128) realLength += 1
    else realLength += 2

    if (realLength <= len) {
      result += str[i]
    }
  }
  return result
}

export function getAssetDataClassEnum(root) {
  const leafs = []

  const dfs = (node) => {
    leafs.push(node)
    if (!node.children || node.children.length === 0) {
      return
    }

    node.children.forEach((item) => dfs(item))
  }
  dfs(root)

  return leafs.map((x) => ({
    code: x.key,
    name: `${x.key} ${x.name}`
  }))
}

export function getAssetDataClassLeaf(root) {
  const leafs = []

  const dfs = (node) => {
    if (!node.children || node.children.length === 0) {
      leafs.push(node)
      return
    }

    node.children.forEach((item) => dfs(item))
  }
  dfs(root)

  return leafs.map((x) => ({
    code: x.key,
    name: `${x.key} ${x.name}`
  }))
}

export function checkIPValid(ip) {
  return /^$|^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(
    ip
  )
}
